/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Timers;
using System.Windows.Threading;

namespace myBoard.Framework.Jobs
{
    public class Job
    {
        BackgroundWorker _bgWorker;
        DoWorkEventHandler _codeToExecute;
        TimeSpan _interval;
        TimeSpan _timeout;
        DispatcherTimer _jobTimer;
        DispatcherTimer _timeoutTimer;
        object _workerArg;
        string _name;
        public delegate void OnProgressChanged(Job sender, ProgressChangedEventArgs progressArgs);
        public delegate void OnRunWorkerCompleted(Job sender, RunWorkerCompletedEventArgs args);
        public event OnProgressChanged ProgressChanged;
        public event OnRunWorkerCompleted RunWorkerCompleted;

        public string Name
        {
            get { return _name; }
        }

        public BackgroundWorker BgWorker
        {
            get { return _bgWorker; }
            set { _bgWorker = value; }
        }

        #region Constructors

        public Job(string name, DoWorkEventHandler codeToExecute)
        {
            Init(name, codeToExecute, null, TimeSpan.Zero, TimeSpan.Zero);
        }

        public Job(string name, DoWorkEventHandler codeToExecute,object arg)
        {
            Init(name, codeToExecute, arg, TimeSpan.Zero, TimeSpan.Zero);
        }

        public Job(string name, DoWorkEventHandler codeToExecute,object arg, TimeSpan interval)
        {
            Init(name, codeToExecute, arg, interval, TimeSpan.Zero);
        }

        public Job(string name, DoWorkEventHandler codeToExecute,object arg, TimeSpan interval, TimeSpan timeout)
        {
            Init(name, codeToExecute, arg, interval, timeout);
        }

        private void Init(string name, DoWorkEventHandler codeToExecute,object arg, TimeSpan interval, TimeSpan timeout)
        {
            _codeToExecute = codeToExecute;
            _interval = interval;
            _timeout = timeout;
            _name = name;
            _workerArg = arg;
            _bgWorker = new BackgroundWorker();
            _bgWorker.WorkerSupportsCancellation = true;
            _bgWorker.WorkerReportsProgress = true;
        }

        #endregion

        private void StartBackgroundWorker()
        {
            if(_timeoutTimer!=null)
                _timeoutTimer.Start();

            _bgWorker.DoWork -= new DoWorkEventHandler(_codeToExecute);
            _bgWorker.DoWork += new DoWorkEventHandler(_codeToExecute);
            _bgWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            _bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            _bgWorker.ProgressChanged -= new ProgressChangedEventHandler(BgWorker_ProgressChanged);
            _bgWorker.ProgressChanged += new ProgressChangedEventHandler(BgWorker_ProgressChanged);
            _bgWorker.RunWorkerAsync(_workerArg);
        }

        void BgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (ProgressChanged != null)
                ProgressChanged(this, e);
        }

        public void StartJob()
        {
            if (_interval != TimeSpan.Zero)
            {
                if (_jobTimer == null)
                {
                    _jobTimer = new DispatcherTimer();
                    _jobTimer.Interval = _interval;
                    _jobTimer.Tick += new EventHandler(JobTimer_Tick);
                }
            }

            if (_timeout != TimeSpan.Zero)
            {
                if (_timeoutTimer == null)
                {
                    _timeoutTimer = new DispatcherTimer();
                    _timeoutTimer.Interval = _timeout;
                    _timeoutTimer.Tick += new EventHandler(JobTimeoutTimer_Tick);
                }
            }

            if (!_bgWorker.IsBusy)                
                StartBackgroundWorker();
            
            if(_jobTimer!=null)
                _jobTimer.Start();
        }

        public void StopJob()
        {
            _jobTimer.Stop();
            _timeoutTimer.Stop();
        }

        private void Abort()
        {
            if (_bgWorker != null)
                _bgWorker.CancelAsync();
        }

        void JobTimer_Tick(object sender, EventArgs e)
        {
            if (_bgWorker.IsBusy)
                Abort();

            if (!_bgWorker.IsBusy)
                StartBackgroundWorker();
        }

        void JobTimeoutTimer_Tick(object sender, EventArgs e)
        {
            Abort();
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(_timeoutTimer!=null)
                _timeoutTimer.Stop();

            if (RunWorkerCompleted != null)
                RunWorkerCompleted(this, e);
        }
    }
}
